package com.geeyuu.android.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.geeyuu.android.GeeApplication;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.customview.wheel.AbstractWheelTextAdapter;
import com.geeyuu.android.customview.wheel.OnWheelChangedListener;
import com.geeyuu.android.customview.wheel.WheelView;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;

public class RegisterUserInfoActivity extends BaseActivity {

    private WheelView wheelView;
    private MyWheelAdapter myWheelAdapter;
    private View wheelViewContainer;
    private int currentWheelItemIndex;
    private int currentButtonChoice;

    private Button ageButton;
    private Button heightButton;
    private Button weightButton;

    private String[] ages = null;
    private String[] heights = null;
    private String[] weights = null;

    private String nickName;
    private String age;
    private String height;
    private String weight;
    private int role = BaseUserInfo.ROLE_NONE;

    private View leftButton;
    private View centerButton;
    private View rightButton;

    private PopupWindow popupWindow;
    private View anchor = null;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "RegisterUserInfoActivity";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_user_info_layout);

        GeePrefrence.setIsUserRegisted(getApplicationContext(), true);
        
        GeeApplication geeApplication = (GeeApplication) getApplication();
        geeApplication.addActivity(this);

        super.isForbidBackKey = true;

        initTitleViews();
        initContentViews();
        
        startBindService();
        
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (wheelViewContainer.getVisibility() == View.VISIBLE) {
                initDownAnimationTranslate();
            }
            AndroidUtil.hideKeyBoard(this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        switch (cmd) {
        case ProtocolCommand.CMD_SET_MY_USER_INFO:
            if (isMsgNormal) {
                Intent intent = new Intent(RegisterUserInfoActivity.this, RegisterAvatarActivity.class);
                startActivity(intent);
                finish();
            } else {
                AndroidUtil.showToast(getApplicationContext(), "提交失败，请重试");
            }
            break;
        }
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.top_right_button:

                showProgressDialog("设置信息", "提交信息中，请稍等", true);
                Bundle bundle = new Bundle();
                bundle.putString(DataKey.S_KEY_USERINFO_NICKNAME, nickName);
                bundle.putString(DataKey.S_KEY_USERINFO_AGE, age);
                bundle.putString(DataKey.S_KEY_USERINFO_HEIGHT, height.replace("cm", "").trim());
                bundle.putString(DataKey.S_KEY_USERINFO_WEIGHT, weight.replace("kg", "").trim());
                bundle.putString(DataKey.S_KEY_USERINFO_ROLE, String.valueOf(role));
                sendMsgToService(ProtocolCommand.CMD_SET_MY_USER_INFO, bundle);

                break;
            case R.id.age_button:
                AndroidUtil.hideKeyBoard(RegisterUserInfoActivity.this);
                anchor = v;
                scrollView.smoothScrollTo(0, 0);
                initAgeWheelView();
                break;
            case R.id.height_button:
                AndroidUtil.hideKeyBoard(RegisterUserInfoActivity.this);
                anchor = v;
                scrollView.smoothScrollTo(0, anchor.getHeight());
                initHeightWheelView();
                break;
            case R.id.weight_button:
                AndroidUtil.hideKeyBoard(RegisterUserInfoActivity.this);
                anchor = v;
                scrollView.smoothScrollTo(0, anchor.getHeight() * 2);
                initWeightWheelView();
                break;
            case R.id.comfire:
                if (currentButtonChoice == 0) {
                    ageButton.setText("年龄   " + ages[currentWheelItemIndex]);
                    age = ages[currentWheelItemIndex];
                } else if (currentButtonChoice == 1) {
                    heightButton.setText("身高   " + heights[currentWheelItemIndex]);
                    height = heights[currentWheelItemIndex];
                } else if (currentButtonChoice == 2) {
                    weightButton.setText("体重   " + weights[currentWheelItemIndex]);
                    weight = weights[currentWheelItemIndex];
                }
                initDownAnimationTranslate();
                break;
            case R.id.cancel:
                initDownAnimationTranslate();
                break;
            case R.id.role_one:
                leftButton.setBackgroundResource(R.drawable.ls_bg);
                centerButton.setBackgroundResource(R.drawable.c_bg);
                rightButton.setBackgroundResource(R.drawable.r_bg);
                role = BaseUserInfo.ROLE_1;
                break;
            case R.id.role_zero:
                leftButton.setBackgroundResource(R.drawable.l_bg);
                centerButton.setBackgroundResource(R.drawable.cs_bg);
                rightButton.setBackgroundResource(R.drawable.r_bg);
                role = BaseUserInfo.ROLE_0;
                break;
            case R.id.role_05:
                leftButton.setBackgroundResource(R.drawable.l_bg);
                centerButton.setBackgroundResource(R.drawable.c_bg);
                rightButton.setBackgroundResource(R.drawable.rs_bg);
                role = BaseUserInfo.ROLE_05;
                break;
            }
        }
    };

    private void initDownAnimationTranslate() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
            scrollView.smoothScrollTo(0, 0);
        }
    }

    private void initTitleViews() {
        Button next = (Button) findViewById(R.id.top_right_button);
        next.setText("下一步");
        next.setVisibility(View.VISIBLE);
        next.setOnClickListener(mOnClickListener);

        Button topLeftButton = (Button) findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.logo_icon47, 0);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 5), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if (null == vl) {
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        } else {
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);
        topLeftButton.setOnClickListener(mOnClickListener);

        TextView topLeftTextView = (TextView) findViewById(R.id.top_left_text_view);
        topLeftTextView.setText("注册第二步");
        topLeftTextView.setVisibility(View.VISIBLE);
    }

    private void initContentViews() {
        findViewById(R.id.step_line0).setBackgroundResource(R.drawable.corners_four_blue_bg);
        findViewById(R.id.step_line1).setBackgroundResource(R.drawable.corners_four_blue_bg);

        leftButton = findViewById(R.id.role_one);
        leftButton.setOnClickListener(mOnClickListener);
        centerButton = findViewById(R.id.role_zero);
        centerButton.setOnClickListener(mOnClickListener);
        rightButton = findViewById(R.id.role_05);
        rightButton.setOnClickListener(mOnClickListener);

        scrollView = (ScrollView) findViewById(R.id.scroll_view);

        EditText nickNameEt = (EditText) findViewById(R.id.nick_name);
        nickNameEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                nickName = s.toString();
                if (null != nickName && nickName.length() > 0) {
                    nickName.trim().replace(" ", "");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        nickNameEt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                return false;
            }
        });

        ageButton = (Button) findViewById(R.id.age_button);
        ageButton.setOnClickListener(mOnClickListener);

        heightButton = (Button) findViewById(R.id.height_button);
        heightButton.setOnClickListener(mOnClickListener);
        weightButton = (Button) findViewById(R.id.weight_button);
        weightButton.setOnClickListener(mOnClickListener);

        wheelViewContainer = getLayoutInflater().inflate(R.layout.register_baseinfo_popup_layout,
                (ViewGroup) findViewById(R.id.all_container), false);
        Button comfire = (Button) wheelViewContainer.findViewById(R.id.comfire);
        comfire.setOnClickListener(mOnClickListener);
        Button cancel = (Button) wheelViewContainer.findViewById(R.id.cancel);
        cancel.setOnClickListener(mOnClickListener);
        wheelView = (WheelView) wheelViewContainer.findViewById(R.id.wheel_view);
        wheelView.setVisibleItems(5);
        wheelView.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                currentWheelItemIndex = newValue;
            }
        });
        popupWindow = new PopupWindow(wheelViewContainer, WindowManager.LayoutParams.FILL_PARENT,
                WindowManager.LayoutParams.FILL_PARENT);
        myWheelAdapter = new MyWheelAdapter(this);

    }

    private void initAgeWheelView() {
        if (null == ages) {
            ages = new String[83];
            for (int i = 17; i < 100; i++) {
                ages[i - 17] = String.valueOf(i);
            }
        }
        currentButtonChoice = 0;
        showWheelView(ages, 8);
    }

    private void initHeightWheelView() {
        if (null == heights) {
            heights = new String[110];
            for (int i = 140; i < 250; i++) {
                heights[i - 140] = String.valueOf(i) + " cm";
            }
        }
        currentButtonChoice = 1;
        showWheelView(heights, 30);
    }

    private void initWeightWheelView() {
        if (null == weights) {
            weights = new String[210];
            for (int i = 40; i < 250; i++) {
                weights[i - 40] = String.valueOf(i) + " kg";
            }
        }
        currentButtonChoice = 2;
        showWheelView(weights, 80);
    }

    private void showWheelView(String[] param, int initIndex) {
        myWheelAdapter.setItemData(param);
        wheelView.setViewAdapter(myWheelAdapter);
        wheelView.setCurrentItem(initIndex);

        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        popupWindow.showAsDropDown(anchor);
    }

    private class MyWheelAdapter extends AbstractWheelTextAdapter {

        private String[] data;

        protected MyWheelAdapter(Context context) {
            super(context, R.layout.wheel_item_layout, R.id.wheel_item_text);
        }

        public void setItemData(String[] param) {
            data = param;
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            return view;
        }

        @Override
        public int getItemsCount() {
            return data.length;
        }

        @Override
        protected CharSequence getItemText(int index) {
            return data[index];
        }
    }

    @Override
    protected void onDestroy() {
        stopBindService();
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        super.onDestroy();
    }

}
